package club.ruanx.movie.service.impl;


import club.ruanx.acl.common.exception.UserException;
import club.ruanx.bean.PageBean;
import club.ruanx.core.service.base.BaseServiceImpl;
import club.ruanx.exception.BaseException;
import club.ruanx.movie.entity.UserFavorite;
import club.ruanx.movie.repository.UserFavoriteRepository;
import club.ruanx.movie.service.UserFavoriteService;
import club.ruanx.security.bean.UserAuthInfo;
import club.ruanx.security.bean.UserAuthInfoContextHolder;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 阮胜
 * @date 2018/11/11 19:50
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserFavoriteServiceImpl extends BaseServiceImpl<UserFavorite, String, UserFavoriteRepository> implements UserFavoriteService {
    @Override
    public UserFavorite favorite(String movieId) throws UserException {
        UserAuthInfo user = UserAuthInfoContextHolder.getCurrentUserAuthInfoThrow();
        return repository.findByUserIdAndMovieId(user.getUid(), movieId).orElseGet(() -> {
            UserFavorite favorite = UserFavorite.builder().userId(user.getUid()).movieId(movieId).build();
            return repository.save(favorite);
        });
    }

    @Override
    public UserFavorite unfavorite(String movieId) throws BaseException {
        String uid = UserAuthInfoContextHolder.getCurrentUserAuthInfoThrow().getUid();
        UserFavorite userFavorite = repository.findByUserIdAndMovieId(uid, movieId)
                .orElseThrow(() -> new BaseException("找不到该电影的收藏记录"));
        repository.deleteById(userFavorite.getId());
        return userFavorite;
    }

    @Override
    public boolean isfavorite(String movieId) throws BaseException {
        String uid = UserAuthInfoContextHolder.getCurrentUserAuthInfoThrow().getUid();
        return repository.existsByUserIdAndMovieId(uid, movieId);
    }

    @Override
    public Page<UserFavorite> findAllByUserId(String uid, PageBean pageBean) {
        return repository.findAllByUserIdOrderByCreateTimeDesc(uid, pageBean.toPageable());
    }
}
